﻿namespace IBTrader.Modules.HistoricalData
{
    using IBTrader.Model;
    using IBTrader.Modules.Tws;
    using NLog;
    using System;
    using System.Threading;

    class Data
    {
        private static readonly Logger logger = LogManager.GetCurrentClassLogger();
        internal event Action Next;
        private readonly HistoricalData main;
        private readonly IIB ib;
        private readonly HistoricalContract contract;
        internal Data(HistoricalData main, IIB ib, HistoricalContract contract)
        {
            this.main = main;
            this.ib = ib;
            this.contract = contract;
        }
        internal void Request()
        {
            if (Next != null) Next();
            if (TestMode)
            {
                // test mode
                ThreadPool.QueueUserWorkItem(_ => main.Next());
                return;
            }
            var endDateTime = main.Contract.DateTime.Add(contract.BarDuration).ToString("yyyyMMdd HH:mm:ss EST");
            var duration = contract.BarDuration.Days > 0 ? string.Format("{0} D", contract.BarDuration.Days) : contract.BarDuration.TotalSeconds.ToString();
            logger.Debug("reqHistoricalData: Symbol {0} Expiry {1} duration {2} endDateTime {3}", contract.Symbol, contract.Expiry, duration, endDateTime);
            ib.reqHistoricalData(
                1,
                main.Contract.CreateContract(),
                endDateTime,            // endDateTime
                duration,               // duration [S]econds (default) [D]ays [W]eeks
                contract.BarSize,           // bar size, minimum 1 sec
                contract.BarType,           // whattoshow so "TRADES", "MIDPOINT", "BID", "ASK", "BID_ASK",
                contract.OnlyRealTime ? 1 : 0,   // 1 only real time hours, 0 also pre/after market
                2);                     // date time format 1 = yyyymmdd... 2 = timestamp
        }
        private bool TestMode { get { return false /* !ib.IsConnected()*/; } }
        internal void Cancel()
        {
            if (TestMode) return; // test mode
            ib.cancelHistoricalData(1);
        }
    }
}